package com.baizhi.interceptor;

import com.baizhi.util.JwtUtil;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map;

public class JwtInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        Map<String,Object> map=new HashMap<>();
        String token = request.getHeader("token");
        try {
            JwtUtil.verify(token);
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            map.put("msg","无效的token");
            map.put("state",401);
        }
        String s = new ObjectMapper().writeValueAsString(map);
        response.setContentType("application/json;charset=utf-8");
        response.getWriter().println(s);
        return false;
    }
}
